package org.funtester.performance.books.chapter10.section3;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.funtester.performance.books.chapter06.section2.MySqlBase;

/**
 * MySQL工厂类
 */
public class MySqlFactory extends BasePooledObjectFactory<MySqlBase> {

    public String url;// 数据库连接地址

    public String user;// 用户名

    public String password;// 密码

    public MySqlFactory(String url, String user, String password) {
        this.url = url;
        this.user = user;
        this.password = password;
    }

    @Override
    public MySqlBase create() throws Exception {
        MySqlBase sqlBase = new MySqlBase(this.url, this.user, this.password);// 创建MySQL基础类
        sqlBase.init();// 初始化资源
        return sqlBase;
    }

    @Override
    public PooledObject<MySqlBase> wrap(MySqlBase mySqlBase) {
        return new DefaultPooledObject<>(mySqlBase);
    }

    @Override
    public void destroyObject(PooledObject<MySqlBase> p) throws Exception {
        super.destroyObject(p);
        p.getObject().close();// 关闭资源
    }

}
